<?php

class SON_Plugins_CheckAcl extends Zend_Controller_Plugin_Abstract
{
    private $_acl = null;

    public function __construct(Zend_Acl $acl)
    {
        $this->_acl = $acl;
    }

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName();
        $resource = $request->getControllerName();
        $action = $request->getActionName();
        
        $auth = Zend_Auth::getInstance();
        $auth->setStorage(new Zend_Auth_Storage_Session($module));
        
        $role = $auth->hasIdentity() ? $auth->getStorage()->read()->role : 'guest';
        	
        if ($this->_acl->has($module . ':' . $resource)) {
        	
        	if (!$this->_acl->isAllowed($role, $module . ':' . $resource, $action)) {
        		
        		if ($role == 'guest') {
        			$request->setModuleName($module)
		        			->setControllerName('auth')
		        			->setActionName('index');
        		} else {
	        		$request->setModuleName($module)
			        		->setControllerName('index')
			        		->setActionName('index');
        		}
        	}
        }
    }
}
